<template>
  <div class='modify-company-container'>
    <div v-for="(company, companyIndex) in companyTypeList"
         class="item-container"
         :key="companyIndex">
      <div v-for="(item, index) in companyInfo[company.type].data"
           :key="index"
           class="company-item">
        <h2>{{company.name}}{{index+1}}
          <i v-if="index===0"
             @click="addCompany(company.type)"
             class="fa fa-plus-circle float-right">
          </i>
          <i v-if="index!==0"
             @click="removeCompany(company.type,index)"
             class="fa fa-minus-circle float-right">
          </i>
        </h2>
        <el-form :model="item"
                 label-width="120px">
          <el-form-item :label="company.name">
            <!-- 当type为1时，必须通过下拉选择公司，type为2时，可通过下拉选择，也可以手动输入公司
             -->
            <el-select v-if="companyInfo[company.type].type===1"
                       remote
                       filterable
                       :remote-method="searchCompany"
                       @focus="getCompanyType(companyInfo[company.type].company_type)"
                       @change="chooseCompany(item.company_info)"
                       v-model="item.company_info.companyObj"
                       value-key="value"
                       class="col-12">
              <el-option v-for="(item) in companyList"
                         :key="item.company_id"
                         :label="item.company_name"
                         :value="item">
              </el-option>
            </el-select>
            <el-autocomplete v-if="companyInfo[company.type].type!==1"
                             @select="val=>{selectCompany(item.company_info,val)}"
                             :fetch-suggestions="(query,cb)=>{searchCompanyName(query,cb,item.company_info,companyInfo[company.type].company_type)}"
                             v-model="item.company_info.company_name"></el-autocomplete>
          </el-form-item>
          <el-form-item label="关联项目部"
                        v-if="item.dept_info">
            <el-input @focus="showOrganizationDialog(company.type,index)"
                      readonly
                      v-model="item.dept_info.dept_name">
            </el-input>
          </el-form-item>
          <el-form-item label="项目负责人"
                        v-if="item.project_leader">
            <el-select @remove-tag="removeLeader(item.project_leader,item.project_leader_name)"
                       @focus="showLeaderDialog(company.type,'project_leader',index)"
                       multiple
                       v-model="item.project_leader_name"
                       class="col-12">
            </el-select>
          </el-form-item>
          <el-form-item label="质量负责人"
                        v-if="item.quality_leader">
            <el-select @focus="showLeaderDialog(company.type,'quality_leader',index)"
                       v-model="item.quality_leader_name"
                       multiple
                       class="col-12">
            </el-select>
          </el-form-item>
          <el-form-item label="设计负责人"
                        v-if="item.design_leader">
            <el-select @focus="showLeaderDialog(company.type,'design_leader',index)"
                       v-model="item.design_leader_name"
                       multiple
                       class="col-12">
            </el-select>
          </el-form-item>
          <el-form-item label="生产负责人"
                        v-if="item.product_leader">
            <el-select @focus="showLeaderDialog(company.type,'product_leader',index)"
                       v-model="item.product_leader_name"
                       multiple
                       class="col-12">
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="btn-groups">
      <el-button @click="previousStep"
                 type="primary">上一步</el-button>
      <el-button type="primary">保存</el-button>
      <el-button @click="submitCompanyInfo"
                 type="primary">下一步</el-button>
    </div>
    <!-- 关联项目部弹框 -->
    <el-dialog title="关联项目部"
               class="organization-dialog"
               :visible.sync="organizationDialogVisible">
      <OrganizationTree :curMenu.sync="selectedNode"></OrganizationTree>
      <div class="dialog-footer">
        <el-button @click="organizationDialogVisible=false">取消</el-button>
        <el-button type="primary"
                   @click="selectDept">确定</el-button>
      </div>
    </el-dialog>
    <!-- 选择项目负责人或质量负责人弹框 -->
    <el-dialog title="选择负责人"
               class="organization-dialog"
               width="60%"
               @close="leaderDialogClose"
               :visible.sync="selectLeaderDialogVisible">
      <div class="choose-leader-container">
        <OrganizationTree ref="selectLeader"
                          :curMenu.sync="selectLeaderNode"
                          :checkbox="false"></OrganizationTree>
        <JobUserList ref="jobUserList"
                     :checkbox="true"
                     :showEditRow="false"
                     :requestParam="getJobUserListParam"></JobUserList>
      </div>

      <div class="dialog-footer">
        <el-button @click="leaderDialogClose">取消</el-button>
        <el-button type="primary"
                   @click="selectLeader">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import OrganizationTree from '@/components/OrganizationTree/OrganizationTree'
import { organizationApi } from '@/services/CompanySetting'
import { ProjectListApi } from '@/services/ProjectCenter'
import { userPermissionApi } from '@/services/UserPermission'
import JobUserList from '@/pages/ConfigCenter/CompanySetting/components/JobUserList'
export default {
  data () {
    return {
      companyInfo: {
        // 施工单位
        construction: {
          data: [
            {
              company_info: {
                company_id: '',
                org_no: '',
                company_name: '',
                company_type: '',
                business_type: '',
                company_addr: '',
                contact_name: '',
                contact_phone: ''
              },
              dept_info: {
                dept_id: '',
                dept_name: ''
              },
              project_leader: [

              ],
              project_leader_name: [],
              product_leader: [

              ],
              product_leader_name: []
            }
          ],
          type: 1,
          company_type: 6
        },
        // 设计单位
        design: {},
        // 构件加工厂
        handle: {},
        // 建设单位
        build: {},
        // 勘测单位
        survey: {},
        // 监理单位
        supervisor: {}
      },
      companyTypeList: [
        { type: 'construction', name: '施工单位' },
        { type: 'design', name: '设计单位' },
        { type: 'handle', name: '构件加工厂' },
        { type: 'build', name: '建设单位' },
        { type: 'survey', name: '勘测单位' },
        { type: 'supervisor', name: '监理单位' }
      ],
      tempCompanyInfo: {
        company_info: {
          company_id: '',
          org_no: '',
          company_name: '',
          company_type: '',
          business_type: '',
          company_addr: '',
          contact_name: '',
          contact_phone: ''
        },
        dept_info: {
          dept_id: '',
          dept_name: ''
        },
        project_leader: [

        ],
        project_leader_name: [],
        product_leader: [

        ],
        product_leader_name: []
      },
      // 关联项目部弹框是否可见
      organizationDialogVisible: false,
      // 当前选择的组织树节点数据
      selectedNode: {},
      // 关联项目部的单位类型
      selectDeptType: '',
      // 关联项目部单位列表index
      selectDeptIndex: 0,
      // 选择项目负责人或质量负责人弹框是否可见
      selectLeaderDialogVisible: false,
      // 选择负责人时的组织树节点数据
      selectLeaderNode: {},
      // 选中的岗位列表数据
      selectLeaderNodeList: [],
      // 选择负责人时的单位类型
      selectLeaderCompany: '',
      // 当前操作的是项目负责人还是单位负责人
      selectLeaderType: '',
      // 选择负责人时的index
      selectLeaderIndex: 0,
      // 搜索公司时，当前所在公司的公司type
      currCompanyType: 0,
      // 搜索到的公司列表
      companyList: [],
      // 获取人员列表请求参数
      getJobUserListParam: {
        org_no: '',
        dept_no: '',
        job_id: '',
        node_type: '',
        user_name: '',
        is_page: 1,
        page: 1,
        page_size: 10
      }
    }
  },
  props: {
    callback: Function,
    projectId: Number,
    previousCallback: Function
  },
  components: {
    OrganizationTree,
    JobUserList
  },
  watch: {
    selectLeaderNode: {
      handler (newval, oldval) {
        let tempData = {}
        tempData.node_type = newval.node_type
        tempData.user_name = ''
        if (newval.node_type === '1') {
          tempData.org_no = newval.org_no
        } else if (newval.node_type === '2') {
          tempData.dept_no = newval.no
        } else if (newval.node_type === '3') {
          tempData.job_id = newval.id
        }
        this.getJobUserListParam = Object.assign(this.getJobUserListParam, tempData)
        console.log(newval, this.getJobUserListParam, 'watch')
      },
      deep: true
    }
  },
  methods: {
    // 提交数据
    submitCompanyInfo () {
      console.log(this.companyInfo)
      this.companyInfo.id = this.projectId
      ProjectListApi.linkProject({
        data: this.companyInfo
      }).then(res => {
        console.log(res, 'link project')
        if (res.code === 0) {
          this.$message.success('新建项目成功')
          this.$emit('success', { step: 3, id: this.projectId })
        }
      }, err => {
        console.log(err)
      })
    },
    // 回到上一步
    previousStep () {
      this.$emit('previousCallback', {
        step: 1,
        id: this.projectId
      })
    },
    test (item) {
      console.log(item)
    },
    // 展示组织树弹框
    showOrganizationDialog (type, index) {
      this.organizationDialogVisible = true
      this.selectDeptType = type
      this.selectDeptIndex = index
    },
    // 选择部门
    selectDept () {
      console.log(this.selectedNode, 'select dept')
      if (this.selectedNode.node_type !== '2') {
        this.$message.error('请选择部门')
      } else {
        // 需要赋值的输入框
        let targetInput = this.companyInfo[this.selectDeptType].data[this.selectDeptIndex].dept_info
        targetInput.dept_id = this.selectedNode.id
        targetInput.dept_name = this.selectedNode.name
        this.organizationDialogVisible = false
      }
    },
    // 展示选择负责人弹框
    showLeaderDialog (companyType, leaderType, index) {
      console.log('focus')
      this.selectLeaderCompany = companyType
      this.selectLeaderType = leaderType
      this.selectLeaderIndex = index
      this.selectLeaderDialogVisible = true
    },
    // 选择负责人
    selectLeader () {
      let selectedRow = this.$refs.jobUserList.getCheckedRow()
      // let checkedNode = this.$refs.selectLeader.$refs.organizationTree.getCheckedNodes()
      this.selectLeaderNodeList = selectedRow
      // 需要赋值的负责人下拉框
      let targetLeader = this.companyInfo[this.selectLeaderCompany].data[this.selectLeaderIndex]
      let leaderList = []
      let nameList = []
      selectedRow.map((item) => {
        leaderList.push({
          user_id: item.user_id,
          user_name: item.user_name
        })
        nameList.push(item.user_name)
      })
      targetLeader[this.selectLeaderType] = leaderList
      targetLeader[this.selectLeaderType + '_name'] = nameList
      this.selectLeaderDialogVisible = false
      console.log(this.companyInfo, selectedRow, 'select')
    },
    // 移除已选择的负责人
    removeLeader (leader, leaderName) {
      leader.map((item, index) => {
        if (!leaderName.includes(item.user_name)) leader.splice(index, 1)
      })
      console.log(leader, leaderName, this.companyInfo, 'remove tag')
    },
    // 关闭选择负责人弹框,关闭时清空复选框
    leaderDialogClose () {
      // 获取组织树组件对象
      let organizationTree = this.$refs.selectLeader.$refs.organizationTree
      this.selectLeaderNodeList.map((item) => {
        organizationTree.setChecked(item, false)
      })
      this.selectLeaderNodeList = []
      this.selectLeaderDialogVisible = false
    },
    // 添加公司
    addCompany (companyType) {
      let newCompanyInfo = JSON.parse(JSON.stringify(this.tempCompanyInfo))
      let targetCompanyInfo = {}
      // 获取第一个数据的keys，根据keys生成新的item
      let keys = Object.keys(this.companyInfo[companyType].data[0])
      keys.map((key) => {
        targetCompanyInfo[key] = newCompanyInfo[key]
      })
      this.companyInfo[companyType].data.push(targetCompanyInfo)
    },
    // 移除公司
    removeCompany (companyType, index) {
      this.companyInfo[companyType].data.splice(index, 1)
    },
    // 搜索公司时，获取目标输入框所在公司的公司类型
    getCompanyType (type) {
      this.currCompanyType = type
    },
    // type为1时，根据单位名下拉搜索，先通过后台接口搜索，没有再调用公共中心接口
    searchCompany (query) {
      ProjectListApi.searchCompany({
        params: {
          project_id: this.projectId,
          company_name: query,
          company_type: this.currCompanyType
        }
      }).then(res => {
        console.log(res, 'search company')
        if (res.code === 0) {
          if (res.data.data.length === 0) {
            this.searchCompanyFromConsole(query)
          } else {
            this.companyList = res.data.data
          }
        }
      }, err => {
        console.log(err)
      })
    },
    // type不为1时，通过单位名搜索，只需要通过后台接口搜索，如果没有允许用户手动输入
    searchCompanyName (query, cb, companyInfo, companyType) {
      ProjectListApi.searchCompany({
        params: {
          project_id: this.projectId,
          company_name: query,
          company_type: companyType
        }
      }).then(res => {
        console.log(res, 'search company')
        if (res.code === 0) {
          res.data.data.map((item) => {
            item.value = item.company_name
          })
          cb(res.data.data)
        }
      }, err => {
        console.log(err)
      })
    },
    // 当后台的接口没有搜索到数据时，请求公共中心的接口
    searchCompanyFromConsole (companyName) {
      userPermissionApi.checkCompanyExists({
        data: {
          multi_para: [
            { company_name: companyName }
          ]
        }
      }).then(res => {
        console.log(res, 'search company from console')
        if (res.code === 0) {
          this.companyList = res.data
        }
      }, err => {
        console.log(err)
      })
    },
    // 选择搜索出来的公司
    chooseCompany (companyInfo) {
      companyInfo = Object.assign(companyInfo, companyInfo.companyObj)
      if (companyInfo.area) {
        companyInfo.company_addr = companyInfo.province + companyInfo.city + companyInfo.area + companyInfo.addr
      }
      console.log(companyInfo, this.companyInfo, 'choose company')
    },
    // 对应类型为2的输入框选择搜索出来的公司时的事件
    selectCompany (companyInfo, val) {
      companyInfo = Object.assign(companyInfo, val)
      console.log(companyInfo, val, 'select company')
    },
    // 获取组织树数据
    getOrgTree () {
      organizationApi.getOrgTree({
        data: {
          node_type: '2'
        }
      }).then(res => {
        // console.log(res, 'get org tree')
        let data = res.data
        console.log(data, 'handle data')
        this.$store.dispatch('setOrgainzationTree', data)
        window.localStorage.setItem('platformOrganizationTree', JSON.stringify(data))
      }, err => {
        console.log(err)
      })
    },
    // 获取项目详情
    getProjectDetail () {
      ProjectListApi.getProjectCompanyInfo({
        params: {
          id: this.projectId || 1
          // id: 1
        }
      }).then(res => {
        // console.log(res, 'get project detail')
        if (res.code === 0) {
          // 初始化数据

          let companyData = res.data
          let values = Object.values(companyData)
          let companyType = {}
          // 首先遍历外层的6种公司类型
          for (companyType of values) {
            if (companyType.data.length > 0) {
              //  再遍历每种公司类型下具体的公司
              companyType.data.map((company) => {
                this.$set(company.company_info, 'companyObj', JSON.parse(JSON.stringify(company.company_info)))
                // company.company_info.companyObj = JSON.parse(JSON.stringify(company.company_info))
                this.initLeaderInput(company, 'design')
                this.initLeaderInput(company, 'project')
                this.initLeaderInput(company, 'product')
              })
            }
          }
          this.companyInfo = companyData
          console.log(this.companyInfo, values, 'companyInfo')
        }
      })
    },
    // 获取项目详情时为项目负责人、设计负责人、质量负责人输入框初始化数据
    initLeaderInput (company, leaderType) {
      if (company[leaderType + '_leader']) {
        company[leaderType + '_leader_name'] = []
        company[leaderType + '_leader'].map((item) => {
          company[leaderType + '_leader_name'].push(item.user_name)
        })
      }
    }

  },
  created () {
    this.getProjectDetail()
    this.getOrgTree()
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
.modify-company-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  .el-autocomplete {
    width: 100%;
  }
  .item-container {
    width: 80%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    .company-item {
      width: 70%;
      height: auto;
      // min-height: 300px;
      background-color: #efefef;
      border-radius: 10px;
      padding: 15px;
      margin-bottom: 20px;
      h2 {
        margin-bottom: 20px;
        i {
          cursor: pointer;
        }
      }
      .el-form-item {
        width: 50%;
      }
    }
  }

  .btn-groups {
    width: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .organization-dialog {
    .choose-leader-container {
      display: flex;
      justify-content: flex-start;
      .menu-tree-container {
        width: 300px;
        margin-right: 20px;
      }
      .staff-list-container {
        width: 800px;
      }
    }
    .dialog-footer {
      text-align: center;
    }
  }
}
</style>
